import { defineStore } from 'pinia'
import { ref, computed } from 'vue'


export const useAuthStore = defineStore('auth', () => {
  // token + userInfo 初始值
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))

  const isLoggedIn = computed(() => !!token.value)

  function login(data) {
    token.value = data.token
    userInfo.value = data.userInfo || {}
    localStorage.setItem('token', data.token)
    localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
  }

  function logout() {
    token.value = ''
    userInfo.value = {}
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }

  // **新增**：合并更新 userInfo 中的字段，并同步 localStorage
  function updateUser(patch) {
    userInfo.value = { ...userInfo.value, ...patch }
    localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
  }



  return {
    token,
    userInfo,
    isLoggedIn,
    login,
    logout,
    updateUser,    // <— 导出这个 action
  }
})
